package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
//为所有 final 字段和标记为 @NonNull 的字段自动生成一个构造函数。
@RequiredArgsConstructor
// 启用并注册 AuthProperties 类作为配置属性类
@EnableConfigurationProperties(AuthProperties.class)
public class GloableTokenFilter implements GlobalFilter, Ordered {

    // 认证属性
    private final AuthProperties authProperties;
    // jwt工具类
    private final JwtTool jwtTool;
    // 路径匹配器
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();
        // 获取响应
        ServerHttpResponse response = exchange.getResponse();
        //从authProperties获取排除路径列表
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            //使用AntPathMatcher判断请求路径是否匹配某个排除路径
            if (antPathMatcher.match(excludePath, path)) {
                //若匹配成功，调用chain.filter(exchange)放行请求并返回
                return chain.filter(exchange);
            }
        }
        //这段代码用于从HTTP请求的Authorization头中提取JWT令牌
        String token = request.getHeaders().getFirst("Authorization");
        if (token == null) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete() ;
        }
        Long userId = null;
        try {
            //调用了jwtTool.parseToken(token)方法，用于解析JWT令牌并提取其中的用户ID
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //把userId添加到请求头中继续发送到微服务中
        /*
        request.mutate() 是 Spring WebFlux 中的一个方法，用于创建一个可变的请求构建器（Builder），
        允许我们修改原始的 HTTP 请求。
        */
        request.mutate().header("user-info", userId.toString());
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        //数值越小优先级越高
        return 0;
    }
}
